// content.js - 语雀文档内容提取和转换脚本
console.log('语雀转Markdown插件已注入');

// HTML到Markdown转换器
class YuqueToMarkdownConverter {
    constructor() {
        this.markdown = '';
        this.listStack = [];
        this.tableState = {
            inTable: false,
            headers: [],
            rows: []
        };
    }
    
    // 主要转换函数
    convertToMarkdown(element) {
        this.markdown = '';
        this.processElement(element);
        return this.markdown.trim();
    }
    
    // 处理HTML元素
    processElement(element) {
        if (!element) return;
        
        const tagName = element.tagName?.toLowerCase();
        
        switch (tagName) {
            case 'h1':
                this.addText(`# ${this.getTextContent(element)}\n\n`);
                break;
            case 'h2':
                this.addText(`## ${this.getTextContent(element)}\n\n`);
                break;
            case 'h3':
                this.addText(`### ${this.getTextContent(element)}\n\n`);
                break;
            case 'h4':
                this.addText(`#### ${this.getTextContent(element)}\n\n`);
                break;
            case 'h5':
                this.addText(`##### ${this.getTextContent(element)}\n\n`);
                break;
            case 'h6':
                this.addText(`###### ${this.getTextContent(element)}\n\n`);
                break;
            case 'p':
                this.processParagraph(element);
                break;
            case 'strong':
            case 'b':
                this.addText(`**${this.getTextContent(element)}**`);
                break;
            case 'em':
            case 'i':
                this.addText(`*${this.getTextContent(element)}*`);
                break;
            case 'code':
                this.addText(`\`${this.getTextContent(element)}\``);
                break;
            case 'pre':
                this.processCodeBlock(element);
                break;
            case 'blockquote':
                this.processBlockquote(element);
                break;
            case 'ul':
                this.processList(element, false);
                break;
            case 'ol':
                this.processList(element, true);
                break;
            case 'li':
                this.processListItem(element);
                break;
            case 'a':
                this.processLink(element);
                break;
            case 'img':
                this.processImage(element);
                break;
            case 'table':
                this.processTable(element);
                break;
            case 'hr':
                this.addText('\n---\n\n');
                break;
            case 'br':
                this.addText('\n');
                break;
            case 'div':
                // 处理div元素，可能包含各种内容
                this.processChildren(element);
                // 如果div后面有内容，添加换行
                if (element.nextSibling) {
                    this.addText('\n');
                }
                break;
            case 'span':
                // 处理span元素，通常是行内格式
                this.processChildren(element);
                break;
            case 'mark':
                // 处理高亮文本
                this.addText(`==${this.getTextContent(element)}==`);
                break;
            case 'del':
            case 's':
                // 处理删除线
                this.addText(`~~${this.getTextContent(element)}~~`);
                break;
            case 'u':
                // 处理下划线（Markdown不支持，用强调代替）
                this.addText(`**${this.getTextContent(element)}**`);
                break;
            case 'kbd':
                // 处理键盘按键
                this.addText(`\`${this.getTextContent(element)}\``);
                break;
            case 'sub':
                // 处理下标
                this.addText(`~${this.getTextContent(element)}~`);
                break;
            case 'sup':
                // 处理上标
                this.addText(`^${this.getTextContent(element)}^`);
                break;
            default:
                // 检查是否有特殊的CSS类
                if (element.classList) {
                    if (element.classList.contains('ne-text-bold') || 
                        element.style.fontWeight === 'bold' ||
                        element.style.fontWeight === '700') {
                        this.addText(`**${this.getTextContent(element)}**`);
                    } else if (element.classList.contains('ne-text-italic') || 
                               element.style.fontStyle === 'italic') {
                        this.addText(`*${this.getTextContent(element)}*`);
                    } else if (element.classList.contains('ne-text-underline') || 
                               element.style.textDecoration === 'underline') {
                        this.addText(`**${this.getTextContent(element)}**`);
                    } else if (element.classList.contains('ne-text-linethrough') || 
                               element.style.textDecoration === 'line-through') {
                        this.addText(`~~${this.getTextContent(element)}~~`);
                    } else if (element.classList.contains('ne-text-code') || 
                               element.classList.contains('inline-code')) {
                        this.addText(`\`${this.getTextContent(element)}\``);
                    } else {
                        this.processChildren(element);
                    }
                } else {
                    this.processChildren(element);
                }
                break;
        }
    }
    
    // 处理段落
    processParagraph(element) {
        const text = this.getInlineContent(element);
        if (text.trim()) {
            this.addText(`${text}\n\n`);
        }
    }
    
    // 处理行内内容
    getInlineContent(element) {
        let content = '';
        
        for (const child of element.childNodes) {
            if (child.nodeType === Node.TEXT_NODE) {
                content += child.textContent;
            } else if (child.nodeType === Node.ELEMENT_NODE) {
                const tagName = child.tagName.toLowerCase();
                
                switch (tagName) {
                    case 'strong':
                    case 'b':
                        content += `**${this.getTextContent(child)}**`;
                        break;
                    case 'em':
                    case 'i':
                        content += `*${this.getTextContent(child)}*`;
                        break;
                    case 'code':
                        content += `\`${this.getTextContent(child)}\``;
                        break;
                    case 'a':
                        const href = child.getAttribute('href') || '';
                        const text = this.getTextContent(child);
                        content += `[${text}](${href})`;
                        break;
                    case 'img':
                        const src = child.getAttribute('src') || '';
                        const alt = child.getAttribute('alt') || '';
                        content += `![${alt}](${src})`;
                        break;
                    case 'span':
                        content += this.getInlineContent(child);
                        break;
                    default:
                        content += this.getTextContent(child);
                        break;
                }
            }
        }
        
        return content;
    }
    
    // 处理代码块
    processCodeBlock(element) {
        const codeElement = element.querySelector('code');
        const language = this.getCodeLanguage(element);
        const code = codeElement ? codeElement.textContent : element.textContent;
        
        this.addText(`\`\`\`${language}\n${code}\n\`\`\`\n\n`);
    }
    
    // 获取代码语言
    getCodeLanguage(element) {
        const classList = element.classList;
        for (const className of classList) {
            if (className.startsWith('language-')) {
                return className.replace('language-', '');
            }
        }
        return '';
    }
    
    // 处理引用块
    processBlockquote(element) {
        const text = this.getTextContent(element);
        const lines = text.split('\n');
        for (const line of lines) {
            if (line.trim()) {
                this.addText(`> ${line}\n`);
            }
        }
        this.addText('\n');
    }
    
    // 处理列表
    processList(element, isOrdered) {
        this.listStack.push({ ordered: isOrdered, index: 0 });
        this.processChildren(element);
        this.listStack.pop();
        this.addText('\n');
    }
    
    // 处理列表项
    processListItem(element) {
        const depth = this.listStack.length - 1;
        const listInfo = this.listStack[depth];
        const indent = '  '.repeat(depth);
        
        let bullet;
        if (listInfo.ordered) {
            listInfo.index++;
            bullet = `${listInfo.index}.`;
        } else {
            bullet = '-';
        }
        
        this.addText(`${indent}${bullet} `);
        this.processChildren(element);
        this.addText('\n');
    }
    
    // 处理链接
    processLink(element) {
        const href = element.getAttribute('href') || '';
        const text = this.getTextContent(element);
        this.addText(`[${text}](${href})`);
    }
    
    // 处理图片
    processImage(element) {
        const src = element.getAttribute('src') || '';
        const alt = element.getAttribute('alt') || '';
        this.addText(`![${alt}](${src})`);
    }
    
    // 处理表格
    processTable(element) {
        const rows = element.querySelectorAll('tr');
        const tableData = [];
        
        for (const row of rows) {
            const cells = row.querySelectorAll('td, th');
            const rowData = [];
            
            for (const cell of cells) {
                rowData.push(this.getTextContent(cell).trim());
            }
            
            tableData.push(rowData);
        }
        
        if (tableData.length > 0) {
            // 表头
            const headers = tableData[0];
            this.addText(`| ${headers.join(' | ')} |\n`);
            
            // 分隔线
            this.addText(`| ${headers.map(() => '---').join(' | ')} |\n`);
            
            // 数据行
            for (let i = 1; i < tableData.length; i++) {
                const row = tableData[i];
                this.addText(`| ${row.join(' | ')} |\n`);
            }
            
            this.addText('\n');
        }
    }
    
    // 处理子元素 - 改进版
    processChildren(element) {
        for (const child of element.childNodes) {
            if (child.nodeType === Node.TEXT_NODE) {
                const text = child.textContent;
                if (text && text.trim()) {
                    this.addText(text);
                }
            } else if (child.nodeType === Node.ELEMENT_NODE) {
                this.processElement(child);
            }
        }
    }
    
    // 获取纯文本内容
    getTextContent(element) {
        return element.textContent || '';
    }
    
    // 添加文本
    addText(text) {
        this.markdown += text;
    }
}

// 提取语雀文档内容 - 重新设计
function extractYuqueContent() {
    console.log('开始提取语雀文档内容...');
    
    // 先尝试直接通过页面内容提取
    let extractedContent = tryExtractByInnerText();
    if (extractedContent) {
        console.log('通过innerText提取成功');
        return extractedContent;
    }
    
    // 尝试通过DOM结构提取
    extractedContent = tryExtractByDomStructure();
    if (extractedContent) {
        console.log('通过DOM结构提取成功');
        return extractedContent;
    }
    
    // 最后尝试通过复制功能
    extractedContent = tryExtractByClipboard();
    if (extractedContent) {
        console.log('通过剪贴板提取成功');
        return extractedContent;
    }
    
    throw new Error('无法提取文档内容，请确保在语雀文档页面');
}

// 方法1：通过innerText提取（最简单但可能丢失格式）
function tryExtractByInnerText() {
    try {
        // 获取页面的主要内容区域
        const contentSelectors = [
            '.ne-viewer-body',
            '.ne-editor-body', 
            '.ant-typography',
            '.doc-content',
            'main',
            'article'
        ];
        
        for (const selector of contentSelectors) {
            const element = document.querySelector(selector);
            if (element) {
                console.log(`使用选择器: ${selector}`);
                
                // 获取纯文本内容
                const textContent = element.innerText || element.textContent;
                if (textContent && textContent.trim().length > 50) {
                    
                    // 简单的格式化处理
                    let formatted = textContent
                        .replace(/\n{3,}/g, '\n\n')  // 清理多余空行
                        .trim();
                    
                    // 添加标题
                    const title = getDocumentTitle();
                    if (title) {
                        formatted = `# ${title}\n\n${formatted}`;
                    }
                    
                    return formatted;
                }
            }
        }
        
        return null;
    } catch (error) {
        console.error('innerText提取失败:', error);
        return null;
    }
}

// 方法2：通过DOM结构提取（保留格式）
function tryExtractByDomStructure() {
    try {
        const contentSelectors = [
            '.ne-viewer-body',
            '.ne-editor-body',
            '.ant-typography',
            '.doc-content',
            '.content-body',
            'main',
            'article'
        ];
        
        for (const selector of contentSelectors) {
            const element = document.querySelector(selector);
            if (element) {
                console.log(`使用DOM结构提取: ${selector}`);
                console.log('元素内容预览:', element.innerHTML.substring(0, 200));
                
                // 使用改进的转换器
                const converter = new ImprovedMarkdownConverter();
                let markdown = converter.convert(element);
                
                if (markdown && markdown.trim().length > 50) {
                    // 添加标题
                    const title = getDocumentTitle();
                    if (title) {
                        markdown = `# ${title}\n\n${markdown}`;
                    }
                    
                    return markdown;
                }
            }
        }
        
        return null;
    } catch (error) {
        console.error('DOM结构提取失败:', error);
        return null;
    }
}

// 方法3：通过模拟全选复制
function tryExtractByClipboard() {
    try {
        // 找到主要内容区域
        const contentSelectors = [
            '.ne-viewer-body',
            '.ne-editor-body',
            '.ant-typography',
            '.doc-content',
            'main',
            'article'
        ];
        
        for (const selector of contentSelectors) {
            const element = document.querySelector(selector);
            if (element) {
                console.log(`尝试全选复制: ${selector}`);
                
                // 创建一个临时的选择范围
                const range = document.createRange();
                range.selectNodeContents(element);
                
                const selection = window.getSelection();
                selection.removeAllRanges();
                selection.addRange(range);
                
                // 获取选中的文本
                const selectedText = selection.toString();
                
                // 清除选择
                selection.removeAllRanges();
                
                if (selectedText && selectedText.trim().length > 50) {
                    // 简单格式化
                    let formatted = selectedText
                        .replace(/\n{3,}/g, '\n\n')
                        .trim();
                    
                    // 添加标题
                    const title = getDocumentTitle();
                    if (title) {
                        formatted = `# ${title}\n\n${formatted}`;
                    }
                    
                    return formatted;
                }
            }
        }
        
        return null;
    } catch (error) {
        console.error('剪贴板提取失败:', error);
        return null;
    }
}

// 改进的Markdown转换器
class ImprovedMarkdownConverter {
    constructor() {
        this.output = '';
    }
    
    convert(element) {
        this.output = '';
        this.processNode(element);
        return this.cleanOutput();
    }
    
    processNode(node) {
        if (!node) return;
        
        if (node.nodeType === Node.TEXT_NODE) {
            const text = node.textContent;
            if (text && text.trim()) {
                this.output += text;
            }
        } else if (node.nodeType === Node.ELEMENT_NODE) {
            this.processElement(node);
        }
    }
    
    processElement(element) {
        const tagName = element.tagName.toLowerCase();
        
        switch (tagName) {
            case 'h1':
                this.output += `\n# ${element.textContent.trim()}\n\n`;
                break;
            case 'h2':
                this.output += `\n## ${element.textContent.trim()}\n\n`;
                break;
            case 'h3':
                this.output += `\n### ${element.textContent.trim()}\n\n`;
                break;
            case 'h4':
                this.output += `\n#### ${element.textContent.trim()}\n\n`;
                break;
            case 'h5':
                this.output += `\n##### ${element.textContent.trim()}\n\n`;
                break;
            case 'h6':
                this.output += `\n###### ${element.textContent.trim()}\n\n`;
                break;
            case 'p':
                this.output += `\n${element.textContent.trim()}\n\n`;
                break;
            case 'strong':
            case 'b':
                this.output += `**${element.textContent.trim()}**`;
                break;
            case 'em':
            case 'i':
                this.output += `*${element.textContent.trim()}*`;
                break;
            case 'code':
                this.output += `\`${element.textContent.trim()}\``;
                break;
            case 'pre':
                this.output += `\n\`\`\`\n${element.textContent.trim()}\n\`\`\`\n\n`;
                break;
            case 'blockquote':
                const lines = element.textContent.trim().split('\n');
                for (const line of lines) {
                    if (line.trim()) {
                        this.output += `> ${line.trim()}\n`;
                    }
                }
                this.output += '\n';
                break;
            case 'ul':
                this.processList(element, false);
                break;
            case 'ol':
                this.processList(element, true);
                break;
            case 'li':
                // 由processList处理
                break;
            case 'a':
                const href = element.getAttribute('href') || '#';
                const text = element.textContent.trim();
                this.output += `[${text}](${href})`;
                break;
            case 'img':
                const src = element.getAttribute('src') || '';
                const alt = element.getAttribute('alt') || '';
                this.output += `![${alt}](${src})`;
                break;
            case 'br':
                this.output += '\n';
                break;
            case 'hr':
                this.output += '\n---\n\n';
                break;
            default:
                // 处理其他元素，递归处理子元素
                for (const child of element.childNodes) {
                    this.processNode(child);
                }
                break;
        }
    }
    
    processList(listElement, isOrdered) {
        const items = listElement.querySelectorAll('li');
        items.forEach((item, index) => {
            const text = item.textContent.trim();
            if (text) {
                if (isOrdered) {
                    this.output += `${index + 1}. ${text}\n`;
                } else {
                    this.output += `- ${text}\n`;
                }
            }
        });
        this.output += '\n';
    }
    
    cleanOutput() {
        return this.output
            .replace(/\n{3,}/g, '\n\n')     // 清理多余空行
            .replace(/\*\*\*\*/g, '**')     // 修复多重加粗
            .replace(/\*\*\s*\*\*/g, '')    // 清理空的加粗标记
            .replace(/\`\`/g, '')           // 清理空的代码标记
            .replace(/\[\]\(\)/g, '')       // 清理空的链接
            .trim();
    }
}

// 获取文档标题 - 增强版
function getDocumentTitle() {
    const titleSelectors = [
        '.ne-viewer-title',
        '.ne-editor-title',
        '.doc-title',
        '.page-title',
        '.yuque-doc-title',
        '.document-title',
        '.content-title',
        '.main-title',
        '[data-testid="doc-title"]',
        '.ant-typography h1',
        '.ne-doc-title',
        'h1.title',
        'h1',
        'title'
    ];
    
    for (const selector of titleSelectors) {
        const element = document.querySelector(selector);
        if (element && element.textContent.trim()) {
            return element.textContent.trim();
        }
    }
    
    // 尝试从URL中提取标题
    const urlTitle = extractTitleFromUrl();
    if (urlTitle) {
        return urlTitle;
    }
    
    return document.title;
}

// 从URL中提取标题
function extractTitleFromUrl() {
    const url = window.location.href;
    const match = url.match(/\/([^\/]+)$/);
    if (match) {
        return decodeURIComponent(match[1]).replace(/[-_]/g, ' ');
    }
    return null;
}

// 监听来自popup的消息
chrome.runtime.onMessage.addListener((request, sender, sendResponse) => {
    console.log('收到消息:', request);
    
    if (request.action === 'convertToMarkdown') {
        try {
            // 添加调试信息
            console.log('=== 页面调试信息 ===');
            console.log('当前URL:', window.location.href);
            console.log('页面标题:', document.title);
            
            // 检查可能的内容选择器
            const testSelectors = [
                '.ne-viewer-body',
                '.ne-editor-body',
                '.ant-typography',
                '.doc-content',
                'main',
                'article'
            ];
            
            console.log('=== 可用选择器检查 ===');
            testSelectors.forEach(selector => {
                const element = document.querySelector(selector);
                if (element) {
                    console.log(`✅ ${selector}: 存在，内容长度=${element.textContent.length}`);
                    console.log(`   类名: ${element.className}`);
                    console.log(`   内容预览: ${element.textContent.substring(0, 100)}...`);
                } else {
                    console.log(`❌ ${selector}: 不存在`);
                }
            });
            
            const markdown = extractYuqueContent();
            
            sendResponse({
                success: true,
                markdown: markdown,
                title: getDocumentTitle()
            });
            
            // 记录转换成功
            chrome.runtime.sendMessage({
                action: 'logUsage',
                data: {
                    url: window.location.href,
                    timestamp: new Date().toISOString(),
                    success: true
                }
            });
            
        } catch (error) {
            console.error('转换失败:', error);
            
            sendResponse({
                success: false,
                error: error.message
            });
            
            // 记录转换失败
            chrome.runtime.sendMessage({
                action: 'logUsage',
                data: {
                    url: window.location.href,
                    timestamp: new Date().toISOString(),
                    success: false,
                    error: error.message
                }
            });
        }
    }
    
    return true; // 保持消息通道开放
});

// 页面加载完成后的初始化
if (document.readyState === 'loading') {
    document.addEventListener('DOMContentLoaded', initialize);
} else {
    initialize();
}

function initialize() {
    console.log('语雀转Markdown插件初始化完成');
    
    // 可以在这里添加一些页面增强功能
    // 比如添加快捷键支持
    document.addEventListener('keydown', function(e) {
        // Ctrl+Shift+M 快速转换
        if (e.ctrlKey && e.shiftKey && e.key === 'M') {
            e.preventDefault();
            console.log('快捷键触发转换');
            
            try {
                const markdown = extractYuqueContent();
                navigator.clipboard.writeText(markdown).then(() => {
                    showNotification('✅ Markdown已复制到剪贴板！');
                }).catch(err => {
                    console.error('复制失败:', err);
                    showNotification('❌ 复制失败，请使用插件按钮');
                });
            } catch (error) {
                console.error('转换失败:', error);
                showNotification('❌ 转换失败: ' + error.message);
            }
        }
    });
}

// 显示通知
function showNotification(message) {
    const notification = document.createElement('div');
    notification.innerHTML = message;
    notification.style.cssText = `
        position: fixed;
        top: 20px;
        right: 20px;
        background: #333;
        color: white;
        padding: 12px 20px;
        border-radius: 6px;
        box-shadow: 0 4px 12px rgba(0,0,0,0.3);
        z-index: 10000;
        font-size: 14px;
        font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, sans-serif;
        animation: slideIn 0.3s ease-out;
    `;
    
    // 添加动画样式
    const style = document.createElement('style');
    style.textContent = `
        @keyframes slideIn {
            from { transform: translateX(100%); opacity: 0; }
            to { transform: translateX(0); opacity: 1; }
        }
        @keyframes slideOut {
            from { transform: translateX(0); opacity: 1; }
            to { transform: translateX(100%); opacity: 0; }
        }
    `;
    document.head.appendChild(style);
    
    document.body.appendChild(notification);
    
    setTimeout(() => {
        notification.style.animation = 'slideOut 0.3s ease-out';
        setTimeout(() => {
            document.body.removeChild(notification);
            document.head.removeChild(style);
        }, 300);
    }, 3000);
} 